home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: free space malloced to auto vars??
- Date: Sat, 3 Feb 1996 21:47:51 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9602032047.AA28443@dxmint.cern.ch>
- References: <4eqf8m$smv@gsusgi1.gsu.edu>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- matmrlx@gsusgi1.gsu.edu (Michael R. Lauer) writes:
-
- >The general question is: if you malloc space for a pointer with automatic
- >storage, should/must you free that space before leaving that scope?
-
- Yes. However, I can't see any malloc call in your example.
- >
- >This seems obvious but it is giving me trouble. In this code:
- >
- >{
- > struct dirent *dp;
- > if ((dp = readdir() != NULL)
- ^^^^^^^^^
- This is a bad function call and it's likely to generate a segmentation
- fault.
- > {
- > }
- > if (dp) /* this seems to cause a segmentation fault */
- > free(dp); /* when the enclosing function returns */
- >}
-
- NEVER free a pointer initialized by a library function (with the possible
- exception of the nonstandard strdup).
- >
- >So readdir returns a pointer to the dirent structure--it is mallocing the
- >space.
-
- Maybe, maybe not. The readdir man page contains no reference to malloc.
-
- >When I leave this scope I AM done with dp and the struct.
-
- A very good reason to call closedir(), which will do all the cleanup for
- you.
-
- >Don't I have to free(dp)? The "if(dp) free(dp)" at the end of the scope caused
- >a segmentation fault when I returned from the enclosing function. It
- >apparently works fine without the free(), but I am worried about memory
- >leakage.
-
- Then call closedir() before returning from the function. If the
- documentation doesn't mention the need to call free(dp), then don't do it.
- If you break the rules, you get what you deserve.
-
- BTW, readdir is not a standard C function, so the question should have been
- posted to comp.unix.programmer.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-